<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农通 - 专家管理</title>
    <link rel="icon" href="./assets/logo.ico" type="images/x-ico" />
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
            /* 上传相关样式 */
    .upload-container {
        margin-top: 10px;
    }
    
    .avatar-preview {
        width: 120px;
        height: 120px;
        border-radius: 50%;
        background-color: #f5f5f5;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        overflow: hidden;
        position: relative;
        border: 2px dashed #ddd;
        margin-bottom: 10px;
    }
    
    .avatar-preview:hover {
        border-color: #4CAF50;
    }
    
    .avatar-preview img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .avatar-preview #avatarPlaceholder {
        text-align: center;
        color: #999;
    }
    
    .avatar-preview #avatarPlaceholder i {
        font-size: 40px;
        display: block;
        margin-bottom: 5px;
    }
    
    .upload-progress {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-top: 10px;
    }
    
    .progress-bar {
        flex: 1;
        height: 6px;
        background-color: #e0e0e0;
        border-radius: 3px;
        overflow: hidden;
    }
    
    .progress {
        height: 100%;
        background-color: #4CAF50;
        width: 0%;
        transition: width 0.3s;
    }
    
    #progressText {
        font-size: 12px;
        color: #666;
    }
        /* 专家管理页面特定样式 */
        .expert-container {
            padding: 20px;
        }
        
        .expert-card {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
            padding: 20px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            transition: transform 0.3s, box-shadow 0.3s;
        }
        
        .expert-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }
        
        .expert-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 20px;
            border: 2px solid #f1f1f1;
        }
        
        .default-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background-color: #f5f5f5;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 20px;
            color: #999;
            font-size: 24px;
            border: 2px solid #f1f1f1;
        }
        
        .expert-info {
            flex: 1;
        }
        
        .expert-name {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .expert-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            margin-bottom: 8px;
        }
        
        .expert-meta-item {
            display: flex;
            align-items: center;
            color: #666;
            font-size: 14px;
        }
        
        .expert-meta-item i {
            margin-right: 5px;
            color: #4CAF50;
        }
        
        .expert-skills {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        
        .skill-tag {
            background-color: #e8f5e9;
            color: #2E7D32;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
        }
        
        .expert-status {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-available {
            background-color: #e8f5e9;
            color: #2E7D32;
        }
        
        .status-booked {
            background-color: #ffebee;
            color: #c62828;
        }
        
        .expert-actions {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 13px;
            cursor: pointer;
            display: flex;
            align-items: center;
            transition: all 0.3s;
        }
        
        .edit-btn {
            background-color: #e3f2fd;
            color: #1565c0;
            border: 1px solid #bbdefb;
        }
        
        .edit-btn:hover {
            background-color: #bbdefb;
        }
        
        .delete-btn {
            background-color: #ffebee;
            color: #c62828;
            border: 1px solid #ffcdd2;
        }
        
        .delete-btn:hover {
            background-color: #ffcdd2;
        }
        
        /* 专家表单模态框 */
        .expert-form .form-group {
            margin-bottom: 15px;
        }
        
        .expert-form .form-row {
            display: flex;
            gap: 15px;
        }
        
        .expert-form .form-row .form-group {
            flex: 1;
        }
        
        .skill-input-container {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .skill-tags-input {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        
        .added-skill {
            background-color: #e3f2fd;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            display: flex;
            align-items: center;
        }
        
        .remove-skill {
            margin-left: 5px;
            cursor: pointer;
            color: #666;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .expert-card {
                flex-direction: column;
                text-align: center;
            }
            
            .expert-avatar, .default-avatar {
                margin-right: 0;
                margin-bottom: 15px;
            }
            
            .expert-meta {
                justify-content: center;
            }
            
            .expert-skills {
                justify-content: center;
            }
            
            .expert-actions {
                justify-content: center;
                margin-top: 15px;
            }
            
            .expert-form .form-row {
                flex-direction: column;
                gap: 0;
            }
        }
    </style>
</head>
<body>
<div class="admin-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <img src="assets/logo.png" alt="惠农通">
                <h2>惠农通</h2>
            </div>
        </div>
        <nav class="sidebar-menu">
            <ul>
                <li data-page="dashboard">
                    <i class="fas fa-chart-line"></i>
                    <span>数据概览</span>
                </li>
                <li data-page="employees">
                    <i class="fas fa-users"></i>
                    <span>员工管理</span>
                </li>
                <li class="active" data-page="expert">
                    <i class="fas fa-user-tie"></i>
                    <span>专家管理</span>
                </li>
                <li  data-page="farm-management">
                    <i class="fas fa-warehouse"></i>
                    <span>农场管理</span>
                </li>
                <li data-page="products">
                    <i class="fas fa-box-open"></i>
                    <span>产品管理</span>
                </li>
                <li data-page="order">
                    <i class="fas fa-shopping-cart"></i>
                    <span>订单管理</span>
                </li>
                <li data-page="ai-chat">
                    <i class="fas fa-robot"></i>
                    <span>AI问答</span>
                </li>
                <li data-page="activities">
                    <i class="fas fa-tractor"></i>
                    <span>农业活动</span>
                </li>
                <li data-page="settings">
                    <i class="fas fa-cog"></i>
                    <span>系统设置</span>
                </li>
            </ul>
        </nav>
        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i>
                <span>退出登录</span>
            </button>
        </div>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
        <header class="main-header">
            <h1 id="pageTitle">专家管理</h1>
            <div class="user-info">
                <span class="welcome">欢迎，<span id="currentUser">管理员</span></span>
                <div class="avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
            </div>
        </header>

        <!-- 专家管理页面内容 -->
        <div class="page-content">
            <div class="page-toolbar">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchExpert" placeholder="输入专家姓名或技能搜索">
                    <button class="search-btn" id="searchExpertBtn">搜索</button>
                </div>
                <button class="primary-btn" id="addExpertBtn">
                    <i class="fas fa-plus"></i> 新增专家
                </button>
            </div>

            <div class="expert-container" id="expertContainer">
                <!-- 专家列表将在这里动态加载 -->
                <div class="loading-overlay" id="loading">
                    <div class="spinner"></div>
                    <span>加载中...</span>
                </div>
            </div>

            <div class="pagination-wrapper">
                <div class="pagination-controls">
                    <button class="page-btn" id="prevPageBtn">
                        <i class="fas fa-chevron-left"></i> 上一页
                    </button>
                    <span class="page-info" id="currentPage">第 1 页</span>
                    <button class="page-btn" id="nextPageBtn">
                        下一页 <i class="fas fa-chevron-right"></i>
                    </button>
                    <select class="page-select" id="pageSize">
                        <option value="5">每页5条</option>
                        <option value="10" selected>每页10条</option>
                        <option value="20">每页20条</option>
                    </select>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 专家表单模态框 -->
<div id="expertModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3 id="modalTitle">新增专家</h3>
            <button class="close-btn" id="closeModalBtn">&times;</button>
        </div>
        <form id="expertForm" class="modal-body expert-form" enctype="multipart/form-data">
            <input type="hidden" id="expertId">
            <div class="form-row">
                <div class="form-group">
                    <label for="modalName">专家姓名</label>
                    <input type="text" id="modalName" class="form-control" placeholder="输入专家姓名" required>
                </div>
                <div class="form-group">
                    <label for="modalPhone">联系电话</label>
                    <input type="tel" id="modalPhone" class="form-control" placeholder="输入联系电话" required>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="modalSex">性别</label>
                    <select id="modalSex" class="form-control" required>
                        <option value="">选择性别</option>
                        <option value="男">男</option>
                        <option value="女">女</option>
                        <option value="其他">其他</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="modalStatus">预约状态</label>
                    <select id="modalStatus" class="form-control" required>
                        <option value="0">可预约</option>
                        <option value="1">已被预约</option>
                    </select>
                </div>
            </div>
            
<!-- 修改头像上传部分的HTML -->
<div class="form-group">
    <label for="modalAvatar">专家头像</label>
    <div class="upload-container">
        <div class="avatar-preview" id="avatarPreview">
            <img id="avatarImage" src="" alt="头像预览" style="display: none;">
            <div id="avatarPlaceholder">
                <i class="fas fa-user-circle"></i>
                <span>点击上传头像</span>
            </div>
        </div>
        <input type="file" id="avatarUpload" accept="image/*" style="display: none;">
        <input type="hidden" id="modalAvatar" name="avatar">
        <div class="upload-progress" id="uploadProgress" style="display: none;">
            <div class="progress-bar">
                <div class="progress" id="progressBar"></div>
            </div>
            <span id="progressText">0%</span>
        </div>
    </div>
</div>
            
            <div class="form-group">
                <label>专业技能</label>
                <div class="skill-input-container">
                    <input type="text" id="skillInput" class="form-control" placeholder="输入技能，按回车添加">
                    <button type="button" class="secondary-btn" id="addSkillBtn">添加</button>
                </div>
                <div class="skill-tags-input" id="skillTagsContainer"></div>
                <input type="hidden" id="modalSkills">
            </div>
            
            <div class="form-group">
                <label for="modalDescription">专家介绍</label>
                <textarea id="modalDescription" class="form-control" rows="4" placeholder="输入专家详细介绍"></textarea>
            </div>
            
            <div class="form-actions">
                <button type="button" class="secondary-btn" id="cancelModalBtn">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" class="primary-btn">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 确认删除对话框 -->
<div id="confirmModal" class="modal">
    <div class="modal-dialog" style="max-width: 400px;">
        <div class="modal-header">
            <h3>确认删除</h3>
            <button class="close-btn" id="closeConfirmModalBtn">&times;</button>
        </div>
        <div class="modal-body">
            <p>确定要删除此专家信息吗？此操作不可撤销。</p>
            <div class="form-actions">
                <button type="button" class="secondary-btn" id="cancelDeleteBtn">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="button" class="primary-btn" id="confirmDeleteBtn">
                    <i class="fas fa-trash-alt"></i> 确认删除
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    // 基础URL配置
    const BASE_URL = 'http://192.168.8.128:8080/admin/expert';
    const token = localStorage.getItem('token');
        // 阿里云OSS配置（这些应该从后端获取，不要在前端硬编码）
        const OSS_CONFIG = {
        region: 'oss-cn-hangzhou', // 您的OSS区域
        bucket: 'your-bucket-name', // 您的Bucket名称
        accessKeyId: '', // 从后端获取
        accessKeySecret: '', // 从后端获取
        stsToken: '', // 从后端获取
        expiration: 0 // 过期时间
    };
    
    // 初始化OSS客户端
    let ossClient = null;
    
    document.addEventListener('DOMContentLoaded', function() {
        // 全局变量
        let currentPage = 1;
        let pageSize = 10;
        let searchKeyword = '';
        let selectedExpertId = null;
        
        
        // DOM元素
        const expertContainer = document.getElementById('expertContainer');
        const loadingOverlay = document.getElementById('loading');
        const prevPageBtn = document.getElementById('prevPageBtn');
        const nextPageBtn = document.getElementById('nextPageBtn');
        const currentPageSpan = document.getElementById('currentPage');
        const pageSizeSelect = document.getElementById('pageSize');
        const searchInput = document.getElementById('searchExpert');
        const searchBtn = document.getElementById('searchExpertBtn');
        const addExpertBtn = document.getElementById('addExpertBtn');
        const expertModal = document.getElementById('expertModal');
        const closeModalBtn = document.getElementById('closeModalBtn');
        const cancelModalBtn = document.getElementById('cancelModalBtn');
        const expertForm = document.getElementById('expertForm');
        const modalTitle = document.getElementById('modalTitle');
        const confirmModal = document.getElementById('confirmModal');
        const closeConfirmModalBtn = document.getElementById('closeConfirmModalBtn');
        const cancelDeleteBtn = document.getElementById('cancelDeleteBtn');
        const confirmDeleteBtn = document.getElementById('confirmDeleteBtn');
        const skillInput = document.getElementById('skillInput');
        const addSkillBtn = document.getElementById('addSkillBtn');
        const skillTagsContainer = document.getElementById('skillTagsContainer');
        
        // 初始化页面
        initPage();
        
        // 事件监听
        prevPageBtn.addEventListener('click', goToPrevPage);
        nextPageBtn.addEventListener('click', goToNextPage);
        pageSizeSelect.addEventListener('change', changePageSize);
        searchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        addExpertBtn.addEventListener('click', showAddExpertModal);
        closeModalBtn.addEventListener('click', hideExpertModal);
        cancelModalBtn.addEventListener('click', hideExpertModal);
        expertForm.addEventListener('submit', handleExpertSubmit);
        closeConfirmModalBtn.addEventListener('click', hideConfirmModal);
        cancelDeleteBtn.addEventListener('click', hideConfirmModal);
        confirmDeleteBtn.addEventListener('click', confirmDeleteExpert);
        addSkillBtn.addEventListener('click', addSkill);
        skillInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                addSkill();
            }
        });

            // 获取OSS上传凭证（从后端）
    async function getOSSToken() {
        try {
            const response = await fetch('/upload'); // 假设后端提供获取凭证的接口
            const data = await response.json();
            
            if (data.code === 1) {
                return data.data;
            } else {
                throw new Error(data.msg || '获取OSS凭证失败');
            }
        } catch (error) {
            console.error('获取OSS凭证失败:', error);
            throw error;
        }
    }
    

        // 设置当前活动菜单项
        function setActiveMenuItem() {
            const currentPage = 'expert'; // 当前页面标识
            
            document.querySelectorAll('.sidebar-menu li').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-page') === currentPage) {
                    item.classList.add('active');
                }
            });
        }
        
        // 页面跳转函数
        function navigateToPage(page) {
            if (page === 'dashboard') {
                window.location.href = 'dashboard.html';
            } else if (page === 'employees') {
                window.location.href = 'employees.html';
            } else if (page === 'products') {
                window.location.href = 'product.html';
            } else if (page === 'expert') {
                window.location.href = 'expert.html';
            } else if (page === 'activities') {
                window.location.href = 'activities.html';
            } else if (page === 'settings') {
                window.location.href = 'settings.html';
            }else if (page === 'expert') {
                window.location.href = 'expert.html';
            }else if(page === 'ai-chat'){
                window.location.href = 'ai-chat.html';
            }else if(page === 'order'){
                window.location.href = 'order.html';
            }else if(page === 'farm-management'){
                window.location.href = 'farm.html';
            }
        }
        
        // 初始化页面
        function initPage() {
            setActiveMenuItem();
            loadExperts();
        

        
            // 添加菜单点击事件
            document.querySelectorAll('.sidebar-menu li').forEach(item => {
                item.addEventListener('click', function() {
                    const page = this.getAttribute('data-page');
                    navigateToPage(page);
                });
            });
        }
    


        
        // 加载专家数据
        function loadExperts() {
            showLoading();
            
            // 构建查询参数
            const params = {
                page: currentPage,
                pageSize: pageSize,
                name: searchKeyword
            };
            
            // 发送请求
            fetch(`${BASE_URL}/page?${new URLSearchParams(params)}`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        renderExperts(data.data);
                        updatePaginationInfo(data.total);
                    } else {
                        alert('加载专家数据失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载专家数据时出错');
                })
                .finally(() => {
                    hideLoading();
                });
        }
        
        // 渲染专家列表
        function renderExperts(pageResult) {
            expertContainer.innerHTML = '';
            
            if (!pageResult || !pageResult.records || pageResult.records.length === 0) {
                const emptyMsg = document.createElement('div');
                emptyMsg.className = 'empty-message';
                emptyMsg.textContent = '没有找到专家数据';
                expertContainer.appendChild(emptyMsg);
                return;
            }
            
            pageResult.records.forEach(expert => {
                const expertCard = document.createElement('div');
                expertCard.className = 'expert-card';
                
                // 头像
                let avatarHtml = '';
                if (expert.avatar) {
                    avatarHtml = `<img src="${expert.avatar}" alt="${expert.name}" class="expert-avatar">`;
                } else {
                    avatarHtml = `<div class="default-avatar">${expert.name.charAt(0)}</div>`;
                }
                
                // 技能标签
                let skillsHtml = '';
                if (expert.skill) {
                    const skills = expert.skill.split(',');
                    skillsHtml = skills.map(skill => 
                        `<span class="skill-tag">${skill.trim()}</span>`
                    ).join('');
                }
                
                // 状态
                const statusClass = expert.status == 1 ? 'status-booked' : 'status-available';
                const statusText = expert.status == 1 ? '已被预约' : '可预约';
                
                expertCard.innerHTML = `
                    ${avatarHtml}
                    <div class="expert-info">
                        <div class="expert-name">${expert.name}
                            <span class="expert-status ${statusClass}">${statusText}</span>
                        </div>
                        <div class="expert-meta">
                            <div class="expert-meta-item"><i class="fas fa-phone"></i> ${expert.phone}</div>
                            <div class="expert-meta-item"><i class="fas fa-venus-mars"></i> ${expert.sex || '未设置'}</div>
                        </div>
                        <div class="expert-skills">${skillsHtml}</div>
                        ${expert.description ? `<p class="expert-desc">${expert.description}</p>` : ''}
                    </div>
                    <div class="expert-actions">
                        <button class="action-btn edit-btn" data-id="${expert.id}">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="action-btn delete-btn" data-id="${expert.id}">
                            <i class="fas fa-trash-alt"></i> 删除
                        </button>
                    </div>
                `;
                
                expertContainer.appendChild(expertCard);
            });


            
            
            // 添加编辑和删除按钮事件
            document.querySelectorAll('.edit-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const expertId = this.getAttribute('data-id');
                    showEditExpertModal(expertId);
                });
            });
            
            document.querySelectorAll('.delete-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const expertId = this.getAttribute('data-id');
                    showConfirmDeleteModal(expertId);
                });
            });




            document.getElementById('avatarPreview').addEventListener('click', function() {
            document.getElementById('avatarUpload').click();
        });
        
        document.getElementById('avatarUpload').addEventListener('change', async function(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // 验证文件类型和大小
            if (!file.type.startsWith('image/')) {
                alert('请上传图片文件');
                return;
            }
            
            if (file.size > 5 * 1024 * 1024) { // 5MB限制
                alert('图片大小不能超过5MB');
                return;
            }
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('avatarImage').src = e.target.result;
                document.getElementById('avatarImage').style.display = 'block';
                document.getElementById('avatarPlaceholder').style.display = 'none';
            };
            reader.readAsDataURL(file);
            
            // 显示上传进度
            document.getElementById('uploadProgress').style.display = 'flex';
            
            try {
                // 创建FormData对象
                const formData = new FormData();
                formData.append('file', file);
                
                // 上传到后端
                const response = await fetch(`http://localhost:8080/upload`, {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    },
                    method: 'POST',
                    body: formData,
                    // 注意：不要手动设置Content-Type，浏览器会自动处理
                });
                
                const result = await response.json();
                
                if (result.code === 1) {
                    // 更新表单字段
                    document.getElementById('modalAvatar').value = result.data;
                } else {
                    throw new Error(result.msg || '上传失败');
                }
            } catch (error) {
                console.error('上传失败:', error);
                alert('头像上传失败，请重试');
                document.getElementById('uploadProgress').style.display = 'none';
            }
        });
    }
        
        // 更新分页信息
        function updatePaginationInfo(total) {
            currentPageSpan.textContent = `第 ${currentPage} 页`;
            
            // 禁用/启用上一页/下一页按钮
            prevPageBtn.disabled = currentPage <= 1;
            nextPageBtn.disabled = currentPage * pageSize >= total;
        }
        
        // 上一页
        function goToPrevPage() {
            if (currentPage > 1) {
                currentPage--;
                loadExperts();
            }
        }
        
        // 下一页
        function goToNextPage() {
            currentPage++;
            loadExperts();
        }
        
        // 改变每页显示数量
        function changePageSize() {
            pageSize = parseInt(pageSizeSelect.value);
            currentPage = 1;
            loadExperts();
        }
        
        // 执行搜索
        function performSearch() {
            searchKeyword = searchInput.value.trim();
            currentPage = 1;
            loadExperts();
        }
        
        // 显示加载中
        function showLoading() {
            loadingOverlay.style.display = 'flex';
        }
        
        // 隐藏加载中
        function hideLoading() {
            loadingOverlay.style.display = 'none';
        }
        
        // 显示新增专家模态框
        function showAddExpertModal() {
            modalTitle.textContent = '新增专家';
            expertForm.reset();
            document.getElementById('expertId').value = '';
            skillTagsContainer.innerHTML = '';
            document.getElementById('modalSkills').value = '';
            expertModal.style.display = 'flex';
        }
        
        // 显示编辑专家模态框
        function showEditExpertModal(expertId) {
            showLoading();
            
            fetch(`${BASE_URL}/${expertId}`,{
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        const expert = data.data;
                        modalTitle.textContent = '编辑专家';
                        document.getElementById('expertId').value = expert.id;
                        document.getElementById('modalName').value = expert.name;
                        document.getElementById('modalPhone').value = expert.phone;
                        document.getElementById('modalSex').value = expert.sex || '';
                        document.getElementById('modalStatus').value = expert.status;
                        document.getElementById('modalAvatar').value = expert.avatar || '';
                        document.getElementById('modalDescription').value = expert.description || '';

                        if (expert.avatar) {
                        document.getElementById('avatarImage').src = expert.avatar;
                        document.getElementById('avatarImage').style.display = 'block';
                        document.getElementById('avatarPlaceholder').style.display = 'none';
                        document.getElementById('modalAvatar').value = expert.avatar;
                    } else {
                        resetAvatarPreview();
                    }
                        
                        // 处理技能
                        skillTagsContainer.innerHTML = '';
                        if (expert.skill) {
                            const skills = expert.skill.split(',');
                            skills.forEach(skill => {
                                if (skill.trim()) {
                                    addSkillToContainer(skill.trim());
                                }
                            });
                            document.getElementById('modalSkills').value = expert.skill;
                        }
                        
                        expertModal.style.display = 'flex';
                    } else {
                        alert('获取专家信息失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('获取专家信息时出错');
                })
                .finally(() => {
                    hideLoading();
                });
        }
        
        // 隐藏专家模态框
        function hideExpertModal() {
            expertModal.style.display = 'none';
        }
        
        // 显示确认删除对话框
        function showConfirmDeleteModal(expertId) {
            selectedExpertId = expertId;
            confirmModal.style.display = 'flex';
        }
        
        // 隐藏确认删除对话框
        function hideConfirmModal() {
            confirmModal.style.display = 'none';
            selectedExpertId = null;
        }

            // 重置头像预览
    function resetAvatarPreview() {
        document.getElementById('avatarImage').src = '';
        document.getElementById('avatarImage').style.display = 'none';
        document.getElementById('avatarPlaceholder').style.display = 'flex';
        document.getElementById('modalAvatar').value = '';
        document.getElementById('avatarUpload').value = '';
    }
    
    // 在showAddExpertModal函数中重置头像预览
    function showAddExpertModal() {
        modalTitle.textContent = '新增专家';
        expertForm.reset();
        document.getElementById('expertId').value = '';
        skillTagsContainer.innerHTML = '';
        document.getElementById('modalSkills').value = '';
        resetAvatarPreview(); // 新增
        expertModal.style.display = 'flex';
    }
        
        // 确认删除专家
        function confirmDeleteExpert() {
            if (!selectedExpertId) return;
            
            showLoading();
            
            fetch(`${BASE_URL}/${selectedExpertId}`, {
                headers: {
                        'Authorization': `Bearer ${token}`
                    },
                method: 'DELETE'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        alert('专家删除成功');
                        loadExperts();
                    } else {
                        alert('删除专家失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('删除专家时出错');
                })
                .finally(() => {
                    hideLoading();
                    hideConfirmModal();
                });
        }
        
        // 处理专家表单提交
        function handleExpertSubmit(e) {
            e.preventDefault();
            
            const expertId = document.getElementById('expertId').value;
            const isEdit = !!expertId;
            
            const expertData = {
                id: expertId,
                name: document.getElementById('modalName').value.trim(),
                phone: document.getElementById('modalPhone').value.trim(),
                sex: document.getElementById('modalSex').value,
                skill: document.getElementById('modalSkills').value,
                status: parseInt(document.getElementById('modalStatus').value),
                avatar: document.getElementById('modalAvatar').value.trim(),
                description: document.getElementById('modalDescription').value.trim()
            };
            
            if (!expertData.name || !expertData.phone) {
                alert('请填写专家姓名和联系电话');
                return;
            }
            
            showLoading();
            
            const url = isEdit ? `${BASE_URL}/${expertId}` : BASE_URL;
            const method = isEdit ? 'PUT' : 'POST';
            
            fetch(url, {
                method: method,
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(expertData)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 1) {
                        alert(`专家${isEdit ? '更新' : '添加'}成功`);
                        hideExpertModal();
                        loadExperts();
                    } else {
                        alert(`${isEdit ? '更新' : '添加'}专家失败: ` + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert(`${isEdit ? '更新' : '添加'}专家时出错`);
                })
                .finally(() => {
                    hideLoading();
                });
        }
        
        // 添加技能
        function addSkill() {
            const skill = skillInput.value.trim();
            if (!skill) return;
            
            addSkillToContainer(skill);
            skillInput.value = '';
        }
        
        // 添加技能到容器
        function addSkillToContainer(skill) {
            const skills = document.getElementById('modalSkills').value;
            const skillsArray = skills ? skills.split(',') : [];
            
            if (!skillsArray.includes(skill)) {
                skillsArray.push(skill);
                document.getElementById('modalSkills').value = skillsArray.join(',');
                
                const skillTag = document.createElement('span');
                skillTag.className = 'added-skill';
                skillTag.innerHTML = `
                    ${skill}
                    <span class="remove-skill" data-skill="${skill}">&times;</span>
                `;
                skillTagsContainer.appendChild(skillTag);
                
                // 添加删除技能事件
                skillTag.querySelector('.remove-skill').addEventListener('click', function() {
                    const skillToRemove = this.getAttribute('data-skill');
                    const updatedSkills = skillsArray.filter(s => s !== skillToRemove);
                    document.getElementById('modalSkills').value = updatedSkills.join(',');
                    skillTag.remove();
                });
            }
        }

        
    });
</script>
</body>
</html>